// pages/radar/wx-chat.js
// pages/radar/radar.js
//获取应用实例
var webim = require('../../utils/webim_wx.js');
var webimhandler = require('../../utils/webim_handler.js');
const app = getApp()
const qiniu = require("../../utils/qiniuCdn.js");
var mtabW;
var ringChart = null;
var selType;
// var selToID = 'ceshi100';
var accountMode = 0;
var loginInfo, accountMode, accountType, sdkAppID, avChatRoomId, selType, selSess, selSessHeadUrl;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        historylist: [],
        msgs: [],
        lastId: '',
        isMore: false,
        formIdArr: [],
        msgContent: "",
        isAutoMsg: false, //自动消息模板
        complete: 0,
        lastMsgTime: 0,
        msgKey: '',
        hideData: [],
        // scrollTop: 0
    },

    onLoad: function(options, e) {
        this.setData(options)
        //去除gwmp前缀
        var start = options.id.lastIndexOf("ll");
        var memberId = options.id.substring(start + 4, options.id.length)
        this.setData({
            options,
            myface: wx.getStorageSync('user').avatarUrl,
            memberId: memberId,
        })
        wx.setNavigationBarTitle({
            title: this.data.options.toname || wx.getStorageSync('store'),
        })
        wx.getSystemInfo({
            success: res => {
                this.setData({
                    scrollHeight: res.windowHeight
                })
            }
        })
        // app.chatLogin==false && this.register()
        this.loadToken()
        var that = this
        var listeners = {
            "onMsgNotify": function(msg) {
                webimhandler.onMsgNotify(msg, function(msgs) {
                    that.receiveMsgs(msgs);
                })
            }
        };
        webim.changeListener(listeners);
        webimhandler.init( this.data.options.id, 1, () => {
            that.pullMsg(1)
        })

    },
    onHide() {
        this.uploadListener()
    },
    onUnload() {
        this.uploadListener()
    },
    /**关闭监听 */
    uploadListener() {
        var listeners = {
            "status": 1
        }
        webim.changeListener(listeners);
    },
    call() {
        wx.makePhoneCall({
            phoneNumber: this.data.options.phone,
        })
    },
    /**
     * 用户注册
     */
    register() {
        app.http.post('city/tiny-station/register-web', {
            data: {
                member_id: this.data.id,
                name: this.data.toname,
                face: this.data.toface
            }
        }).then(res => {


        })
    },
    /**
     * 拉取消息
     */
    pullMsg(otype) {
        let {
            hideData = [], msgs = []
        } = this.data
        var options = {
            'Peer_Account': this.data.options.id, //好友帐号
            'MaxCnt': 10, //拉取消息条数
            'LastMsgTime': this.data.lastMsgTime, //最近的消息时间，即从这个时间点向前拉取历史消息
            'MsgKey': this.data.msgKey
        };
        if (this.data.complete == 1) {
            return
        }
        if (otype == 1) {
            webimhandler.getC2CHistoryMsgs(options, (x, complete, lastMsgTime, msgKey) => {
                console.log(x, options,'eeeeeeee')
                // for (var i in x)
                //     this.receiveMsgs(x[i])
                for (var i = 0; i < x.length; i++) {
                    this.receiveMsgs(x[i])
                }
                this.setData({
                    complete: complete,
                    lastMsgTime: lastMsgTime,
                    msgKey: msgKey,
                })
                this.pullMsg(2)
            })
        } else {
            webimhandler.getC2CHistoryMsgs(options, (x, complete, lastMsgTime, msgKey) => {
                console.log(x, 'otype2xxxxxx')
                for (var i in x)
                    hideData.push(x[i])
                this.setData({
                    hideData,
                    complete: complete,
                    lastMsgTime: lastMsgTime,
                    msgKey: msgKey,
                })
            })
        }
    },
    /**
     * 下拉加载历史消息
     */
    loadHistory(e) {
        console.log(e.target.offsetTop, 'scrollTopxxxxxxxxxxx')
        let {
            loading = false, msgs = [], hideData = [], moreScrollTop = 0
        } = this.data
        if (loading || hideData == '' || !hideData) {
            this.setData({
                NoMoreEvent: 1,
                moreScrollTop: 0,
            })
            return
        }
        if (e.target.offsetTop < 5) {
            // console.log(e.detail.scrollTop, 'scrollTopxxxxxxxxxxx')
            loading = true,
                this.setData({
                    loading,
                })
            //获取隐藏的view 高度
            var query = wx.createSelectorQuery();
            query.select('#hideview').boundingClientRect()
            query.exec(res => {
                msgs = hideData.concat(msgs) //拼接数据
                loading = false //允许再次触发触顶事件
                hideData = []
                moreScrollTop = res[0].height
                this.setData({
                    msgs,
                    loading,
                    hideData,
                    moreScrollTop,
                })
                this.pullMsg(2) //拉取新的隐藏数据
            })
        }

    },
    /**
     * 获取token
     */
    loadToken() {
        app.http.post('city/member/qn-token').then(res => {
            this.setData({
                token: res.data
            })
        }).catch(err => {
            app.wxToast.error(err.message);
        })
    },
    /**
     * 复制内容
     */
    copyText() {
        wx.setClipboardData({
            data: this.data.options.wx,
            success: res => {
                wx.getClipboardData({
                    success: res => {
                        wx.showToast({
                            title: '复制微信号成功'
                        })
                    }
                })
            }
        })
    },
    // 获取容器高度，使页面滚动到容器底部
    pageScrollToBottom: function() {
        wx.getSystemInfo({
            success: res => {
                this.setData({
                    scrollHeight: res.windowHeight
                });
                wx.createSelectorQuery().select('#j_page').boundingClientRect(function(rect) {
                    // 使页面滚动到底部
                    wx.pageScrollTo({
                        scrollTop: rect.bottom,
                    })
                }).exec()
            }
        });

    },


    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        this.pageScrollToBottom()
    },

    /**
     * 
     * im相关函数
     */

    compare: function(obj1, obj2) {
        var val1 = obj1.time;
        var val2 = obj2.time;
        if (val1 < val2) {
            return -1;
        } else if (val1 > val2) {
            return 1;
        } else {
            return 0;
        }
    },

    /**
     * 监听
     */

    receiveMsgs: function(data) {
        var msgs = this.data.msgs ? this.data.msgs : [];
        msgs.push(data);
        this.setData({
            msgs: msgs,
            toView: 'item' + (msgs.length - 1)
        })
    },

    clearInput: function() {
        this.setData({
            content: ""
        })
    },

    bindInput(e) {
        var that = this
        that.setData({
            content: e.detail.value
        })
    },

    onSend: function(e) {
        let {
            content = []
        } = this.data
        var that = this;
        if (!content.replace(/^\s*|\s*$/g, '')) return;
        webimhandler.onSendMsg(content, function(msg) {
            console.log(msg, 'msgxxxxxxxx')
            if (msg === 20003) {
                that.register()
                return
            }
            that.clearInput();
            that.receiveMsgs({
                'fromAccountNick': msg.fromAccountNick,
                'content': content,
                'time': webim.Tool.formatTimeStamp(msg.time),
                'type': msg.elems[0].type,
                'isSend': true
            })
            // 推送消息
            // that.data.memberId && app.sendMsg(that.data.memberId, 1)
        })
    },
    /**
     * 获取formId
     */
    // getFormId: function(e) {
    //     let { formIdArr=[]}=this.data
    //     var formId = e.detail.formId
    //     if (formId != 'the formId is a mock one') {
    //         formIdArr.push(formId)
    //     }
    //     if (formIdArr.length == 5) {
    //         app.http.post('message/save-form-id', {
    //             data: {
    //                 form_id: formIdArr,
    //             },
    //         }).then(res => {
    //             this.setData({
    //                 formIdArr: []
    //             })
    //         })
    //     }
    // },

    /**
     * 更多
     */
    isMore() {
        this.setData({
            isMore: !this.data.isMore
        })
    },
    /**
     * input失去焦点
     */
    checkMore() {
        this.setData({
            isMore: false
        })
    },
    /**
     * 选择图片
     */
    chooseImg() {
        wx.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: res => {
                var tempFilePaths = res.tempFilePaths[0]

                // 上传到七牛
                qiniu.upload(tempFilePaths, this.data.token).then(keys => {
                    var imgUrl = 'https://img.zhxcxmall.com/' + keys[0]
                    var status = webimhandler.sendPic(imgUrl, 0, () => {
                        this.receiveMsgs({
                            fromAccount: 'fromAccountNick',
                            content: imgUrl,
                            isSend: true,
                            time: webim.Tool.formatTimeStamp(Math.round(new Date().getTime() / 1000)),
                            'type': 'TIMImageElem',
                        });
                        this.data.memberId && app.sendMsg(this.data.memberId, 1)
                    })

                }).catch(err => {
                    console.log(err, '上传图片失败')
                })

            }
        })
    },

    /**
     * 查看大图
     */
    seeBigImg(e) {
        let {
            arr = [], msgs, imgArr = []
        } = this.data
        var index = e.currentTarget.dataset.index
        imgArr.push(...msgs.map(o => {
            if (o.content.length != 0 && o.type === 'TIMImageElem') {
                arr.push(o.content)
            }
            return o.content
        }))
        wx.previewImage({
            current: imgArr[index],
            urls: arr
        })
    },

})